package com.atguigu.juc_day02;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther zzyy
 * @create 2022-06-19 16:46
 * CountDownLatch主要有两个方法，当一个或多个线程调用await方法时，这些线程会阻塞。
 * 其它线程调用countDown方法会将计数器减1(调用countDown方法的线程不会阻塞)，
 * 当计数器的值变为0时，因await方法阻塞的线程会被唤醒，继续执行。
 */
class Student{
    private Lock lock = new ReentrantLock ();
    private Condition condition = lock.newCondition ();
    private int number = 6;
    public  void out() throws InterruptedException {
        lock.lock ();
        while (number==0){
            condition.await ();
            //wait ();
        }
        number--;

        System.out.println (Thread.currentThread ().getName ()+"目前剩余"+number);
        lock.unlock ();
        //condition.signal ();
        //notify ();
    }
}
public class CountDownLatchDemo {
    public static void main (String[] args) throws InterruptedException {
        Student student = new Student ();
        CountDownLatch countDownLatch = new CountDownLatch (6);

        for (int i = 0; i < 6; i++) {
            new Thread (()->{
                try {
                    student.out ();
                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
                countDownLatch.countDown ();
            }).start ();
        }
        countDownLatch.await ();

        System.out.println (Thread.currentThread ().getName ()+"班长出门");
    }
}
